package GUI.Productos;

import BE.BELogAudit;
import BE.BEProducto;
import BE.BEUsuario;
import BL.BLCombo;
import BL.BLLogAudit;
import BL.BLProducto;
import BL.BLValidaciones;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.Timestamp;
import java.util.Date;
import javax.swing.JOptionPane;

public class GUIModificarProducto extends javax.swing.JDialog {

    BEProducto producto = null;
    BEUsuario objUsuario;
    /** Creates new form GUIModificarProducto */
    public GUIModificarProducto(java.awt.Frame parent, boolean modal,int idProd) {
        super(parent, modal);
        initComponents();
        this.inicializa();
        this.llenaVentana(idProd);
    }

    GUIModificarProducto(java.awt.Frame object, boolean b, int idProd, BEUsuario Usuario) {
        super(object, b);
        objUsuario= Usuario;
        initComponents();
        this.inicializa();
        this.llenaVentana(idProd);
    }

    public void inicializa()
    {
        BLValidaciones validar = new BLValidaciones();
        
        this.setLocationRelativeTo(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = screenSize.height;
        int width = screenSize.width;
        this.setLocation(width/2-this.getWidth()/2, height/2-this.getHeight()/2);
        
        BLProducto blProd = new BLProducto();
        BLCombo bLCombo = new BLCombo();

        bLCombo.setCombo("TIPOPRODUCTO",1,cmbTipoProcducto);
        bLCombo.setCombo("CONTACTO",1,cmbProveedor);
        blProd.llenarTablaTipoPallet(tblCantidad);
        
        //Caracteristicas del los text fields
        txtStockMinimo.addKeyListener(validar.soloNumeros);
        txtFactor.addKeyListener(validar.soloNumerosReales);
    }

    public void llenaVentana (int idProd)
    {
        BLProducto blProd = new BLProducto();
        producto = blProd.getProdbyId(idProd);

        if (producto != null)
        {
            int i = 0;
            txtNombre.setText(producto.getNombre());
            txtarDescripcion.setText(producto.getDescripcion());
            txtStockMinimo.setText(producto.getStockMin()+"");
            txtFactor.setText(producto.getFactorVencimiento()+"");
            
            for (i=0;i<cmbTipoProcducto.getModel().getSize();i++)
            {
                BLCombo s = (BLCombo)cmbTipoProcducto.getModel().getElementAt(i);
                if (s.id == producto.getIdTipoProducto())
                    break;
            }
            cmbTipoProcducto.setSelectedIndex(i);

            i = 0;
            for (i=0;i<cmbProveedor.getModel().getSize();i++)
            {
                BLCombo s = (BLCombo)cmbProveedor.getModel().getElementAt(i);
                if (s.id == producto.getIdProveedor())
                    break;
            }
            cmbProveedor.setSelectedIndex(i);
            blProd.llenaTablaCantidad(tblCantidad, idProd);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlDatosProducto = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        lblTipoProducto = new javax.swing.JLabel();
        cmbTipoProcducto = new javax.swing.JComboBox();
        lblStock = new javax.swing.JLabel();
        lblDescricpion = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtarDescripcion = new javax.swing.JTextArea();
        lblProveedor = new javax.swing.JLabel();
        cmbProveedor = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblCantidad = new javax.swing.JTable();
        lblStockMin = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtStockMinimo = new javax.swing.JTextField();
        txtFactor = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        btnAgregar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Editar Producto");
        setName("GUIModificarProducto"); // NOI18N

        pnlDatosProducto.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Producto"));

        lblNombre.setText("Nombre:");

        lblTipoProducto.setText("Tipo de Producto:");

        cmbTipoProcducto.setEnabled(false);

        lblStock.setText("Capacidad:");

        lblDescricpion.setText("Descripción:");

        txtarDescripcion.setColumns(20);
        txtarDescripcion.setRows(5);
        jScrollPane1.setViewportView(txtarDescripcion);

        lblProveedor.setText("Proveedor:");

        cmbProveedor.setEnabled(false);

        tblCantidad.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Tipo Pallet", "Cantidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblCantidad.setEnabled(false);
        jScrollPane2.setViewportView(tblCantidad);

        lblStockMin.setText("Stock Minimo:");

        jLabel1.setText("Factor de Vencimiento:");

        jLabel2.setText("[1.0,2.0]");

        jLabel3.setText("1: Vencimiento Acelerado");

        jLabel4.setText("2: Vencimiento Lento");

        javax.swing.GroupLayout pnlDatosProductoLayout = new javax.swing.GroupLayout(pnlDatosProducto);
        pnlDatosProducto.setLayout(pnlDatosProductoLayout);
        pnlDatosProductoLayout.setHorizontalGroup(
            pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDatosProductoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlDatosProductoLayout.createSequentialGroup()
                        .addComponent(lblNombre)
                        .addGap(120, 120, 120)
                        .addComponent(txtNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE))
                    .addGroup(pnlDatosProductoLayout.createSequentialGroup()
                        .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblStockMin)
                            .addComponent(lblStock))
                        .addGap(86, 86, 86)
                        .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtStockMinimo, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)))
                    .addGroup(pnlDatosProductoLayout.createSequentialGroup()
                        .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlDatosProductoLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(28, 28, 28))
                            .addComponent(lblTipoProducto)
                            .addComponent(lblProveedor)
                            .addComponent(lblDescricpion))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(txtFactor, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                            .addComponent(cmbTipoProcducto, 0, 221, Short.MAX_VALUE)
                            .addComponent(cmbProveedor, 0, 221, Short.MAX_VALUE))))
                .addContainerGap())
        );
        pnlDatosProductoLayout.setVerticalGroup(
            pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlDatosProductoLayout.createSequentialGroup()
                .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombre)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblStock)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlDatosProductoLayout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(lblStockMin))
                    .addGroup(pnlDatosProductoLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(txtStockMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtFactor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbTipoProcducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTipoProducto))
                .addGap(18, 18, 18)
                .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblProveedor)
                    .addComponent(cmbProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pnlDatosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDescricpion)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        btnAgregar.setText("Aceptar");
        btnAgregar.setMaximumSize(new java.awt.Dimension(100, 25));
        btnAgregar.setPreferredSize(new java.awt.Dimension(100, 25));
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.setMaximumSize(new java.awt.Dimension(100, 25));
        btnCancelar.setPreferredSize(new java.awt.Dimension(100, 25));
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(pnlDatosProducto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlDatosProducto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
}//GEN-LAST:event_btnCancelarActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        BLProducto blProd = new BLProducto();
        BLValidaciones validar = new BLValidaciones();
        int retorno;
        int procedeFactor = 1;
        int procedeStock = 1;
        boolean cambio = false;

        if (txtFactor.getText().equals(""))
        {
            JOptionPane.showMessageDialog(null,"Debe elegir un factor de vencimiento","Error",JOptionPane.ERROR_MESSAGE);          
            procedeFactor = 0;
        }
        else if (!(Double.parseDouble(txtFactor.getText()) >= 1 && Double.parseDouble(txtFactor.getText()) <= 2)){
            JOptionPane.showMessageDialog(null,"El factor de vencimiento debe estar entre 1 y 2","Error",JOptionPane.ERROR_MESSAGE);          
            procedeFactor = 0;
        }
        else    
            producto.setFactorVencimiento(Double.parseDouble(txtFactor.getText()));
        
        if (txtStockMinimo.getText().equals("")){
            JOptionPane.showMessageDialog(null,"Debe elegir un stock mínimo","Error",JOptionPane.ERROR_MESSAGE);
            procedeStock = 0;
        }
        else
            producto.setStockMin(Integer.parseInt(txtStockMinimo.getText()));
        
        if (!producto.getNombre().equals(txtNombre.getText())) cambio = true;
        producto.setNombre(validar.validarSqlInjection(txtNombre.getText()));
        producto.setDescripcion(validar.validarSqlInjection(txtarDescripcion.getText()));

        if (procedeFactor == 1 && procedeStock == 1)
            retorno = blProd.modificaProducto(producto,cambio);
        else 
            retorno = 1;
        
        if (retorno ==0)
        {
            
            BLLogAudit objgestorAdit = new BLLogAudit();
            BELogAudit objlogAudit= new BELogAudit();
            
            objlogAudit.setIdUsuario(objUsuario.getIdUsuario());
            objlogAudit.setIdInterface(0);
            objlogAudit.setIdUsuario(objUsuario.getIdUsuario());
            objlogAudit.setAccion("Edicion del Producto "+producto.getNombre()+" por el usuario "+objUsuario.getUsuario()+"." );
            Date aux= new Date();
            Timestamp fecha= new Timestamp(aux.getTime());
            
            objlogAudit.setFecha(fecha);
            
            objgestorAdit.registrarAccion(objlogAudit);
            
            JOptionPane.showMessageDialog(null,"Se ha editado el producto",
                                               "Informacion",JOptionPane.INFORMATION_MESSAGE);
            this.dispose();
        }
    }//GEN-LAST:event_btnAgregarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                GUIModificarProducto dialog = new GUIModificarProducto(new javax.swing.JFrame(), true,0);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cmbProveedor;
    private javax.swing.JComboBox cmbTipoProcducto;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblDescricpion;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JLabel lblProveedor;
    private javax.swing.JLabel lblStock;
    private javax.swing.JLabel lblStockMin;
    private javax.swing.JLabel lblTipoProducto;
    private javax.swing.JPanel pnlDatosProducto;
    private javax.swing.JTable tblCantidad;
    private javax.swing.JTextField txtFactor;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtStockMinimo;
    private javax.swing.JTextArea txtarDescripcion;
    // End of variables declaration//GEN-END:variables

}
